package javasec.contempt.dialogs;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class ObjectDialog extends Dialog
{
	String dialogName=null;
	String[] argumentNames=null;
	Class[]  argumentTypes=null;
	Object[] argumentValues=null;

	Text argumentText[]=null;
	Label argumentNameLabel[]=null;
	Label argumentTypeLabel[]=null;

	public boolean aborted=true;

	public ObjectDialog(Shell parent,String dn, String[] an, Class[] at)
	{
		super(parent);
		dialogName=dn;
		argumentNames=an;
		argumentTypes=at;
	}
	
	public Object[] getArguments()
	{
		return argumentValues;
	}
	
	protected void okPressed()
	{
		aborted=false;
		
		argumentValues=new Object[argumentTypes.length];

		System.out.println("candy");
		for(int x=0;x<argumentTypes.length;++x)
		{
			try
			{
				System.out.println("is");
				// TODO this code only valid for strings
				if(argumentTypes[x].getSimpleName().equals("Integer"))
					argumentValues[x]=new Integer(argumentText[x].getText());
				else argumentValues[x]=argumentTypes[x].cast(argumentText[x].getText());
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		System.out.println("good");
		
		super.okPressed();
	}
	
	protected Control createDialogArea(Composite parent)
	{
		
		Composite composite = new Composite(parent,0);
		composite.setLayoutData(new GridData(GridData.FILL_BOTH));
		GridLayout layout= new GridLayout(3,false);
		composite.setLayout(layout);

		if(argumentNames==null)
		{
			new Label(composite,SWT.NONE).setText("arguments not properly set");
			return composite;
		}
		
		// all we have now is argument names and types
		// the dialog will grab the argument values
		int argumentCount=argumentNames.length;
		if(argumentCount<1)
		{
			// TODO verify that this actually does something
			new Label(composite,SWT.NONE).setText("not enough arguments");
			return composite;
		}
	
		argumentText=new Text[argumentCount];
		argumentTypeLabel=new Label[argumentCount];
		argumentNameLabel=new Label[argumentCount];
		
		for(int x=0;x<argumentCount;++x)
		{
			// TODO generalize away from string
			argumentTypeLabel[x]=new Label(composite,SWT.None);
			argumentNameLabel[x]=new Label(composite,SWT.None);
			argumentText[x]=new Text(composite,SWT.LEFT|SWT.BORDER);
			
			argumentTypeLabel[x].setText(argumentTypes[x].getSimpleName());
			argumentNameLabel[x].setText(argumentNames[x]);
			
			argumentText[x].setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		}
		
		return composite;
	}
	
	protected void configureShell(Shell newShell)
	{
		super.configureShell(newShell);
		newShell.setText(dialogName);
	}
}
